const dayjs = require("dayjs");
// const $sql = require("./sql").user;
// const _ = require('./query');

module.exports = {
  saveUserInfo: ({ openId, nickName, gender, language, city, province, country, avatarUrl }, session_key, skey) => {
    const uid = openId,
    crete_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const insertObj = {
      'uid': uid,
      'create_time': crete_time,
      'uname': nickName,
      'ugender': gender,
      'uaddress': province + '/' + country,
      'update_time': crete_time,
      'skey': skey,
      'sessionKey': session_key,
      'uavatar': avatarUrl,
    };
    const updateObj = {
      'uname': nickName,
      'ugender': gender,
      'uaddress': province + '/' + country,
      'update_time': crete_time,
      'skey': skey,
      'sessionKey': session_key,
      'uavatar': avatarUrl,
    }

    let ubalance;
    return _.query($sql.has, [uid]).then(res => {
      console.log(res, 'has');
      if (res.length > 0) {
      // if (res && res[0] && res[0].userCount) {
        // ubalance = res[0].ubalance;
        return _.query($sql.update, [updateObj, uid])
      } else {
        // ubalance = config.credit;
        // ubalance = 0;
        return _.query($sql.insert, insertObj)
      }
    }).then(() => {
      return {
        userInfo:  {
          nickName,
          gender,
          language,
          city,
          province,
          country,
          avatarUrl,
          balance: ubalance,
        },
        skey,
      }
    }).catch(err => {
      console.log("save userInfo error", err);
      return {
        errMsg: JSON.stringify(err)
      }
    })
  },

  getUserId: (skey, content) => {
    return _.query($sqlQury.getId, [skey, content])
  }
};